package com.chy.edu.controller;


import com.chy.commonutils.Result;
import com.chy.edu.client.VodClient;
import com.chy.edu.pojo.EduVideo;
import com.chy.edu.service.EduVideoService;
import com.chy.servicebase.exceptionhandler.GuLiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author chy
 * @since 2020-10-27
 */
@Api(tags = "课程小节管理")
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;
    @Autowired
    private VodClient vodClient;

    @ApiOperation(value = "添加小节")
    @PostMapping("addVideo")
    public Result addVideo(@ApiParam(name = "eduVideo", value = "小节对象", required = true)
                               @RequestBody EduVideo eduVideo)
    {
        videoService.save(eduVideo);
        return Result.ok();
    }

    @ApiOperation(value = "删除小节,删除对应阿里云视频")
    @DeleteMapping("{id}")
    public Result deleteVideo(@ApiParam(name = "id", value = "课时ID", required = true)
                                  @PathVariable String id)
    {
        // 根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = videoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        // 判断小节里面是否有视频id
        if (!StringUtils.isEmpty(videoSourceId)) {
            // 根据视频id，远程调用实现视频删除
            Result result = vodClient.removeAlyVideo(videoSourceId);
            if (result.getCode() == 20001) {
                throw new GuLiException(20001,"删除视频失败，熔断器..");
            }
        }
        videoService.removeById(id);
        return Result.ok();
    }

    @ApiOperation(value = "根据小节id查询")
    @GetMapping("getVideoInfo/{videoId}")
    public Result getChapterInfo(@ApiParam(name = "videoId", value = "小节ID", required = true)
                                 @PathVariable String videoId)
    {
        EduVideo eduVideo = videoService.getById(videoId);
        return Result.ok().data("video",eduVideo);
    }

    @ApiOperation(value = "修改小节")
    @PostMapping("updateVideo")
    public Result updateChapter(@ApiParam(name = "eduVideo", value = "小节对象", required = true)
                                @RequestBody EduVideo eduVideo)
    {
        videoService.updateById(eduVideo);
        return Result.ok();
    }
}

